<?php
session_start();
if(isset($_SESSION['UserID'])) {
	unset($_SESSION['UserID']);
}

if( (!empty($_POST['txtUser']) && !empty($_POST['txtPass'])) || isset($_SESSION['UserID']) )
{
	require_once($_SERVER["DOCUMENT_ROOT"] . '/hotel/common/dao.php'); 
	require $_SERVER["DOCUMENT_ROOT"] . '/hotel/common/inspekt/inspekt.php';

	$user = $_POST['txtUser'];
	$pass = $_POST['txtPass'];
	
	if(!Inspekt::isAlnum($user) || !Inspekt::isAlnum($pass))
	{
		$error = "ERROR: Nombre de usuario o contrase&ntilde;a incorrecta.";
	}
		
	$result = DAO::run_query("SELECT firstname, lastname, roleID, isActive FROM tbl_operator WHERE operatorID='$user' AND password=PASSWORD('$pass')");
	
	if (!$result) 
	{
		die("Error al conectar a la base de datos: <br />" . mysql_error());
	}
	
	if(mysql_num_rows($result) > 0)
	{	
		$userData = mysql_fetch_row($result);
		mysql_free_result($result);
		
		//Check if active
		if($userData[3] == 1)
		{
			//Store user data on session
			$_SESSION['UserID'] = $user;
			$_SESSION['UserName'] = $userData[0].' '.$userData[1];
			$_SESSION['UserRol'] = $userData[2];
			
			//Check on user role and redirect user to right main_menu page
			if($userData[2] == 1) //Normal user
			{
				header('Location: mainMenu.php');
			}
			elseif($userData[2] == 2) //Admin user
			{
				header('Location: mainMenu.php');
			}
		}
		else 
		{
			//Not active
			header("Location: ../accessdenied.php");
		}
	}
	else
	{
		$error = 'ERROR: Nombre de usuario o contrase&ntilde;a incorrecta.';
	}
}	
?>
<html>
	<head>
		<title>Entrada</title>
		<link rel=stylesheet type="text/css" href="../estilo.css">
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">	
	</head>
	<body>
		<div align="left">
			<div align="center">
				<img src="../imagenes/intro.png" width="738" height="378" />
			</div>
			<form name="formulario" method="post" action="login.php">
				<div align="center" class="box">
					<table width="400px" border="0" cellspacing="2" cellpadding="0" align="center">
						<tr>
							<td align="right">Usuario:</td>
							<td>
								<input name="txtUser" type="text"/>
							</td>
						</tr>
						<tr>
							<td align="right">Contrase&ntilde;a:</td>
							<td>
								<input name="txtPass" type="password"/>
							</td>
						</tr>
					</table>
					
					<div align="center" class="error"><?php echo "$error";?></div>
					
					<div align="center">
						<input type="submit" name="Entrar" value="Entrar" >
					</div>
				</div>
				
			</form>
		</div>
	</body>
</html>
